{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# Example: Exporting to $\\LaTeX$\n",
    "\n",
    "The first code block contains the imports needed and defines a flag which determines whether the \n",
    "output $\\LaTeX$ should be compiled."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "import subprocess\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "# Flag to compile output tables\n",
    "compile_latex = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "The next code block loads the npz file created using the output from the Fama-MacBeth example.\n",
    "The second part shows a generic method to restore all variables. The loaded data is in a dictionary,\n",
    "and so iterating over the keys and using `globals()` (a dictionary) in the main program."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Load variables\n",
    "f = np.load(\"fama-macBeth-results.npz\")\n",
    "data = f.items()\n",
    "# Manually load parameters and std errors\n",
    "arp = f[\"arp\"]\n",
    "arp_se = f[\"arp_se\"]\n",
    "beta = f[\"beta\"]\n",
    "beta_se = f[\"beta_se\"]\n",
    "J = f[\"J\"]\n",
    "Jpval = f[\"Jpval\"]\n",
    "\n",
    "# Generic restore of all data in a npz file\n",
    "for key in f.keys():\n",
    "    globals()[key] = f[key]\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "The document is be stored in a list. The first few lines contain the required header for a\n",
    "$\\LaTeX$ document, including some packages used to improve table display and to select a custom font.\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# List to hold table\n",
    "latex = []\n",
    "# Initializd LaTeX document\n",
    "latex.append(r\"\\documentclass[a4paper]{article}\")\n",
    "latex.append(r\"\\usepackage{amsmath}\")\n",
    "latex.append(r\"\\usepackage{booktabs}\")\n",
    "latex.append(r\"\\usepackage[adobe-utopia]{mathdesign}\")\n",
    "latex.append(r\"\\usepackage[T1]{fontenc}\")\n",
    "latex.append(r\"\\begin{document}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "Table 1 is stored in its own list, and then extend will be used to add it to the main list. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Table 1\n",
    "table1 = []\n",
    "table1.append(r\"\\begin{center}\")\n",
    "table1.append(r\"\\begin{tabular}{lrrr} \\toprule\")\n",
    "# Header\n",
    "colNames = [r\"VWM$^e$\", \"SMB\", \"HML\"]\n",
    "header = \"\"\n",
    "for cName in colNames:\n",
    "    header += \" & \" + cName\n",
    "\n",
    "header += r\"\\\\ \\cmidrule{2-4}\"\n",
    "table1.append(header)\n",
    "# Main row\n",
    "row = \"\"\n",
    "for a, se in zip(arp, arp_se):\n",
    "    row += r\" & $\\underset{{({0:0.3f})}}{{{1:0.3f}}}$\".format(se, a)\n",
    "table1.append(row)\n",
    "# Blank row\n",
    "row = r\"\\\\\"\n",
    "table1.append(row)\n",
    "# J-stat row\n",
    "row = r\"J-stat: $\\underset{{({0:0.3f})}}{{{1:0.1f}}}$ \\\\\".format(float(Jpval), float(J))\n",
    "table1.append(row)\n",
    "table1.append(r\"\\bottomrule \\end{tabular}\")\n",
    "table1.append(r\"\\end{center}\")\n",
    "# Extend latex with table 1\n",
    "latex.extend(table1)\n",
    "latex.append(r\"\\newpage\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "Table 2 is a bit more complex, and uses loops to iterate over the rows of the arrays containing\n",
    "the $\\beta$s and their standard errors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Format information for table 2\n",
    "sizes = [\"S\", \"2\", \"3\", \"4\", \"B\"]\n",
    "values = [\"L\", \"2\", \"3\", \"4\", \"H\"]\n",
    "# Table 2 has the same header as table 1, copy with a slice\n",
    "table2 = table1[:3]\n",
    "m = 0\n",
    "for i in range(len(sizes)):\n",
    "    for j in range(len(values)):\n",
    "        row = \"Size: {:}, Value: {:} \".format(sizes[i], values[j])\n",
    "        b = beta[:, m]\n",
    "        s = beta_se[m, 1:]\n",
    "        for k in range(len(b)):\n",
    "            row += r\" & $\\underset{{({0:0.3f})}}{{{1: .3f}}}$\".format(s[k], b[k])\n",
    "        row += r\"\\\\ \"\n",
    "        table2.append(row)\n",
    "        m += 1\n",
    "    if i < (len(sizes) - 1):\n",
    "        table2.append(r\"\\cmidrule{2-4}\")\n",
    "\n",
    "table2.append(r\"\\bottomrule \\end{tabular}\")\n",
    "table2.append(r\"\\end{center}\")\n",
    "# Extend with table 2\n",
    "latex.extend(table2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The penultimate block finished the document, and uses write to write the lines to the $\\LaTeX$ file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Finish document\n",
    "latex.append(r\"\\end{document}\")\n",
    "# Write to table\n",
    "fid = open(\"latex.tex\", \"w\")\n",
    "for line in latex:\n",
    "    fid.write(line + \"\\n\")\n",
    "fid.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, if the flag is set, subprocess is used to compile the LaTeX.\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# Compile if needed\n",
    "if compile_latex:\n",
    "    exit_status = subprocess.call(r\"pdflatex latex.tex\", shell=True)\n",
    "else:\n",
    "    print(\"\\n\".join(latex))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
